package com.margo.project.web.mvcconfig.interceptor;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;




public class MargoEurekaRateLimitInterceptor implements HandlerInterceptor{

	private AtomicInteger totalRequest=new AtomicInteger(0);
	
	private AtomicInteger interceptedRequest=new AtomicInteger(0);
	
	private Logger logger=LoggerFactory.getLogger(this.getClass());
	
	private final MargoEurekaRateLimiter margoEurekaRateLimiter;

    public MargoEurekaRateLimitInterceptor() {
    	margoEurekaRateLimiter= new MargoEurekaRateLimiter(TimeUnit.SECONDS);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	if(request.getRequestURI().endsWith("helloworld")) {
    		totalRequest.getAndIncrement();
        	if (!margoEurekaRateLimiter.acquire(5,2)) {
        		interceptedRequest.getAndIncrement();
            	logger.info(request.getRequestURI()+"请求超过限流器速率");
                return false;
            }
    	}else if(request.getRequestURI().endsWith("total")) {
    		logger.info("请求数"+totalRequest.get());
    		logger.info("被拦截请求数"+interceptedRequest.get());
    	}
    	return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
